package com.credithc.customers.manager.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.credithc.baseserv.core.codes.CoreCodes;
import com.credithc.baseserv.core.message.Message;
import com.credithc.baseserv.core.message.MessageFactory;
import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.customers.base.factory.DictionaryFactory;
import com.credithc.customers.base.po.SystemDictPo;
import com.credithc.customers.base.ro.DictMapperRo;
import com.credithc.customers.base.ro.SystemDictRo;
import com.credithc.customers.base.service.ISystemDictionaryService;
import com.credithc.customers.base.vo.DictMapperVo;
import com.credithc.customers.base.vo.SystemDictVo;
import com.credithc.customers.manager.service.IDictMapperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.websocket.server.PathParam;
import java.util.*;

/**
 * @Title: 系统字典表管理
 * @Author: Denghx
 * @Date: 2018/12/11 15:03
 * @Description: com.credithc.customers.manager.controller
 * @Version: V1.0.0
 */
@RestController
@RequestMapping("/manager/yzt/v1")
public class SystemDictionaryController {
    @Autowired
    MessageFactory messageFactory;
    @Autowired
    ISystemDictionaryService dictionaryService;
    @Autowired
    private IDictMapperService dictMapperService;

    @GetMapping("/dictionary")
    public Message getAllDictonary(@PathParam("type") String type, @PathParam("name") String name, @PathParam("code") String code, @PathParam("sts") String sts, @RequestParam("pageNo") Integer pageNo, @RequestParam("pageSize") Integer pageSize) {
        SystemDictRo dictionary = new SystemDictRo();
        dictionary.setCode(code);
        dictionary.setName(name);
        dictionary.setType(type);
        dictionary.setSts(sts);
        dictionary.setPageNo(pageNo);
        dictionary.setPageSize(pageSize);
        PageInfo<SystemDictVo> list = dictionaryService.selectAll(dictionary);
        Map<String, Object> pageInfo = new HashMap<>();
        pageInfo.put("pageInfo", list);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, pageInfo);
    }

    /**
     * 新增字典
     */
    @PostMapping("/dictionary")
    public Message saveDictonary(@RequestBody @Valid SystemDictRo dictionary) {
        dictionaryService.insert(dictionary);
        DictionaryFactory.refreshDicMap();
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }

    /**
     * 更新字典
     */
    @PostMapping("/dictionary/{id}")
    public Message updateDictonary(@RequestBody @Valid SystemDictRo dictionary, @PathVariable(name = "id") Integer id) {
        dictionaryService.updateDictionary(dictionary, id);
        DictionaryFactory.refreshDicMap();
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }

    @PostMapping("/dictionary/remove/{id}")
    @ResponseBody
    public Message deleteDictonary(@PathVariable(name = "id") Integer id) {
        dictionaryService.remove(id);
        DictionaryFactory.refreshDicMap();
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }

    @PostMapping("/dictionary/remove")
    @ResponseBody
    public Message deleteAll(@RequestBody JSONObject data) {
        System.out.println(data);
        JSONArray jsonArray = data.getJSONArray("ids");
        //把json数据放入到list中
        List list = new ArrayList<>();
        for (Object jstr : jsonArray) {
            list.add(jstr);
        }
        dictionaryService.removeBatch(list);
        DictionaryFactory.refreshDicMap();
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }

    /**
     * @description: 生成字典json数据，主要用于下拉列表等页面控件
     * @date: 2018/12/17 14:43
     * @param: dictType
     * @return: java.lang.String
     */
    @RequestMapping("/manager/dict")
    @ResponseBody
    public String getDictionaryJSON(@RequestParam String type) {
        Map map = null;
        if ("contact".equals(type)) {
            map = DictionaryFactory.Dict.CONTACT_TYPE.getDictMap();
        } else if ("customerType".equals(type)) {
            map = DictionaryFactory.Dict.CUSTOMER_TYPE.getDictMap();
        }
        String result = "";
        if (map != null && !map.isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            Iterator iter = map.keySet().iterator();
            while (iter.hasNext()) {
                Object key = iter.next();
                String value = map.get(key).toString();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("key", key.toString());
                jsonObject.put("value", value);
                jsonArray.add(jsonObject);
            }
            result = jsonArray.toJSONString();
        }
        return result;
    }


    @GetMapping("/dictMapper")
    @ResponseBody
    public Message getDictMapper(@RequestParam(name = "pageNo",defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize",defaultValue = "20") Integer pageSize) {
        Map<String, Object> pageInfo = new HashMap<>();
        PageInfo<DictMapperVo> list = dictMapperService.getMapperList(pageNo, pageSize);
        pageInfo.put("pageInfo", list);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, pageInfo);
    }

    @PostMapping("/dictMapper")
    @ResponseBody
    public Message addDictMapper(@RequestBody @Valid DictMapperRo ro) {
        dictMapperService.insertDictMapper(ro);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }

    @PostMapping("/dictMapper/{id}")
    @ResponseBody
    public Message updateDictMapper(@PathVariable(name = "id") String id,@RequestBody @Valid DictMapperRo ro) {
        dictMapperService.updateDictMapper(id,ro);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }

    @PostMapping("/dictMapper/remove/{id}")
    @ResponseBody
    public Message deleteDictMapper(@PathVariable(name = "id") String id) {
        dictMapperService.deleteDictMapper(id);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }


    @PostMapping("/dictMapper/remove")
    @ResponseBody
    public Message deleteDictMappers(@RequestBody JSONObject data) {
        JSONArray jsonArray = data.getJSONArray("ids");
        List<String> list = new ArrayList<>();
        for (Object str : jsonArray) {
            list.add((String) str);
        }
        dictMapperService.deleteDictMappers(list);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS);
    }

    @GetMapping("/dict/mapperType")
    @ResponseBody
    public Message getMapperType(@RequestParam(name = "type",required = false) String type) {
        PageInfo<SystemDictPo> systemInfoPos =dictionaryService.getMapperType(type);
        Map<String, Object> pageInfo = new HashMap<>();
        pageInfo.put("pageInfo", systemInfoPos);
        return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, pageInfo);
    }

}
